#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/9/19 16:48
# @Author  : AshJo
# @Desc    : 用户类
# @Filename: uesr_obj.py.py
# @Version : v1.0
"""

"""定义一个用户类，用户名和密码是这个类的属性，实例化两个用户，分别有不同的用户名和密码
1.登录成功之后才能创建用户对象
2.设计一个方法 修改密码
"""

import os


def login(username, password, filepath='userinfo'):
    with open(filepath, encoding='utf-8') as f:
        for line in f:
            user, pwd = line.strip().split('|')
            if user == username and pwd == password:
                return True


class User:
    def __init__(self, username, password):
        self.user = username
        self.pwd = password

    def change_pwd(self):
        oldpwd = input('输入旧密码：')
        newpwd = input('输入新密码：')
        flag = False
        with open('userinfo', encoding='utf-8') as f1, open('userinfo.bak', encoding='utf-8', mode='w') as f2:
            for line in f1:
                username, password = line.strip().split('|')
                if username == self.user and password == oldpwd:
                    line = '%s|%s\n' % (username, newpwd)
                    flag = True
                f2.write(line)
        os.remove('userinfo')
        os.rename('userinfo.bak', 'userinfo')
        return flag


while True:
    username = input('用户名：').strip()
    password = input('密码：').strip()
    ret = login(username, password)
    if ret:
        print('登录成功！')
        obj = User(username, password)
        res = obj.change_pwd()
        if res:
            print('修改密码成功！')
        else:
            print('修改密码失败！')
    else:
        print('登录失败！')
        break
